import 'dart:async';

import 'package:dio/dio.dart';
import 'package:event_bus/event_bus.dart';
import 'package:flutter_music/ext/get_extension.dart';
import 'package:flutter_music/http/app_except.dart';
import 'package:flutter_music/utils/log_util.dart';
import 'package:flutter_music/utils/toast_util.dart';
import 'package:get/get.dart';

///具有状态控制和网络请求能力的controller，等价MVVM中的ViewModel
abstract class BaseController<M> extends SuperController with ToastUtil {
  late M api;
  late EventBus eventBus;
  List<StreamSubscription>? _streamSubList;
  RxString barTitleString = "标题".obs;

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
  }
  void loadNet();

  httpRequest<T>(Future<T> future,FutureOr<dynamic> Function(T value) onValue,
  {Function(Exception e)? error,bool showLoading = false,bool handleError = false,
  bool handleSuccess = true}) {
    if(showLoading) {
      Get.showLoading();
    }
    future.then((t) {
      ///添加结果码判断（同时考虑加入List的判断逻辑）
      if(handleSuccess) {
        showSuccess();
      }
      onValue(t);
    }).catchError((e) {
      LogE("网络请求异常====>error:$e");
      if (handleError) {
        showError(e: e);
      }
      if (error != null) {
        error(e);
      }
      showToast(e.toString());
    }).whenComplete(() {
      if(showLoading) {
        Get.dismiss();
      }
    });
  }

  void showSuccess() {
    change(null,status: RxStatus.success());
  }
  void showEmpty() {
    change(null,status: RxStatus.empty());
  }
  void showLoading() {
    change(null, status: RxStatus.loading());
  }

  void showError({String? errorMessage, Exception? e}) {
    if (e != null) {
      if (e is DioException && e.error is AppException) {
        var error = e.error as AppException;
        change(null, status: RxStatus.error(error.message));
      } else {
        change(null, status: RxStatus.error(errorMessage));
      }
    } else {
      change(null, status: RxStatus.error(errorMessage));
    }
  }

  bool useEventBus() => false;

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
    LogD('>>>>>>>onReady');
    if (useEventBus()) {
      eventBus = Get.find<EventBus>();
    }
    try {
      api = Get.find<M>();
    } catch (e) {
      LogE(e.toString());
    }

  }
  @override
  void onClose() {
    // TODO: implement onClose
    disposeEventBus();
    super.onClose();

  }
  void disposeEventBus() {
    _streamSubList?.forEach((element) {
      element.cancel();
    });
  }
  ///管理Eventbus解订阅
  void addStremSub(StreamSubscription? streamSubscription) {
    _streamSubList ??= [];
    if (streamSubscription != null) {
      _streamSubList?.add(streamSubscription);
    }
  }
  @override
  void onDetached() {
    LogD('>>>>>>>onDetached');
  }

  @override
  void onInactive() {
    LogD('>>>>>>>onInactive');
  }

  @override
  void onPaused() {
    LogD('>>>>>>>onPaused');
  }

  @override
  void onResumed() {
    LogD('>>>>>>>onResumed');
  }
  @override
  void onHidden() {
    // TODO: implement onHidden
  }


}